package com.skivingcloud.report.service.impl;

import com.skivingcloud.common.exceptions.BusinessException;
import com.skivingcloud.report.dto.DataSetTransformDto;
import com.skivingcloud.report.service.IGroovyHandler;
import com.skivingcloud.report.service.TransformStrategy;
import groovy.lang.GroovyClassLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class GroovyTransformServiceImpl implements TransformStrategy {
    private static final Logger log = LoggerFactory.getLogger(GroovyTransformServiceImpl.class);

    /**
     * 数据清洗转换 类型
     *
     * @return 类型-javaBean
     */
    @Override
    public String type() {
        return "javaBean";
    }

    /***
     * 清洗转换算法接口
     * @param def 数据集定义
     * @param data 数据
     * @return 转换后结果
     */
    @Override
    public List<Map<String, Object>> transform(DataSetTransformDto def, List<Map<String, Object>> data) {
        String transformScript = def.getTransformScript();
        Class<?> clazz = new GroovyClassLoader().parseClass(transformScript);
        if (clazz != null) {
            try {
                Object instance = clazz.getDeclaredConstructor().newInstance();
                if (instance instanceof IGroovyHandler handler) {
                    return handler.transform(data);
                } else {
                    System.err.println("转换失败！");
                }
            } catch (Exception e) {
                log.info("执行javaBean异常", e);
                throw new BusinessException("执行GROOVY程序失败");
            }
        }
        return data;
    }
}
